﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using AuthorizePolicy.JWT;
using Core.InterFace.Interface;
using coreEntityFramework.Model;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace coreEntityFramework.Controllers
{
    [Route("api/[controller]")]
    //[Authorize("Permission")]
    [EnableCors("MyDomain")]
    public class PermissionController : Controller
    {
        /// <summary>
        /// 自定义策略参数http://www.cnblogs.com/axzxs2001/p/7530929.html
        /// </summary>
        PermissionRequirement _requirement;
       // public IConfiguration Configuration { get; }
        private readonly IAccountService _accountService;

        public PermissionController(IAccountService accountService, PermissionRequirement requirement) //, IConfiguration configuration
        {
            _requirement = requirement;
            _accountService = accountService;
            //Configuration = configuration;
        }

        [AllowAnonymous]
        [HttpGet]
        public IEnumerable<string> get()
        {
            return new string[] { "value1", "value2" };
        }

        [AllowAnonymous]
        [HttpPost("Login")]
        public IActionResult Login([FromBody] LoginDto loginDto)
        {
            ////loginDto.UserName == "gsw" && loginDto.Password == "111111";



            //var isValidated = _accountService.CheckAuth(loginDto.UserName, loginDto.Password);  

            return null;

  
            //if (!isValidated)
            //{
            //    return new JsonResult(new
            //    {
            //        Status = false,
            //        Message = "认证失败"
            //    });
            //}
            //else
            //{
            //    //如果是基于用户的授权策略，这里要添加用户;如果是基于角色的授权策略，这里要添加角色
            //    var claims = new Claim[] { new Claim(ClaimTypes.Name, loginDto.UserName), new Claim(ClaimTypes.Role, loginDto.Role), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) };
            //    //用户标识
            //    var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            //    identity.AddClaims(claims);

            //    var token = JwtToken.BuildJwtToken(claims, _requirement);
            //    return new JsonResult(token);
            //}
        }


        [AllowAnonymous]
        [HttpPost("authenticate")]
        public IActionResult RequestToken([FromBody]TokenRequest request)
        {
            //if (request != null)
            //{
            //    //验证账号密码,这里只是为了demo，正式场景应该是与DB之类的数据源比对
            //    if ("smilesb101".Equals(request.UserName) && "123456".Equals(request.Password))
            //    {
            //        var claims = new[] {
            //            //加入用户的名称
            //            new Claim(ClaimTypes.Name,request.UserName)
            //        };
            //        var audienceConfig = Configuration.GetSection("Audience");
            //        var symmetricKeyAsBase64 = audienceConfig["Secret"];
            //        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(symmetricKeyAsBase64));
            //        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //        var authTime = DateTime.UtcNow;
            //        var expiresAt = authTime.AddDays(7);

            //        var token = new JwtSecurityToken(
            //            issuer: "lilibuy.com",
            //            audience: "lilibuy.com",
            //            claims: claims,
            //            expires: expiresAt,
            //            signingCredentials: creds);

            //        return Ok(new
            //        {
            //            access_token = new JwtSecurityTokenHandler().WriteToken(token),
            //            token_type = "Bearer",
            //            profile = new
            //            {
            //                name = request.UserName,
            //                auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
            //                expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
            //            }
            //        });
            //    }
            //}

            return BadRequest("Could not verify username and password.Pls check your information.");
        }


        [HttpPost("TestJwt")]
        public string TestJwt([FromBody] LoginDto loginDto)
        {
            return "sss";
        }


    }
}